package org.lc.oauth.util;

import cn.hutool.core.codec.Base64;
import jakarta.servlet.http.HttpServletRequest;
import org.lc.platform.base.constant.AuthConstant;
import org.lc.platform.base.enums.AuthResultEnum;
import org.lc.platform.base.enums.LoginResultEnum;
import org.lc.platform.base.exception.BusinessException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * OAuth2 Endpoint 工具类
 *
 * @author dl
 * @since 3.0.0
 */
public class OAuth2EndpointUtils {


    public OAuth2EndpointUtils() {
    }

    public static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
        parameterMap.forEach((key, values) -> {
            for (String value : values) {
                parameters.add(key, value);
            }
        });
        return parameters;
    }


    public static String getClientSign(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String remoteAddr = "";
        String userAgent = request.getHeader("User-Agent");
        remoteAddr = request.getHeader("X-FORWARDED-FOR");
        if (remoteAddr == null || remoteAddr.isEmpty()) {
            remoteAddr = request.getRemoteAddr();
        }
        return Base64.decodeStr(userAgent + ";" + remoteAddr, StandardCharsets.UTF_8);
    }

    public static void throwError(AuthResultEnum res) {
        OAuth2EndpointUtils.throwError(res.getMsg(), res.getCode());
    }

    public static void throwError(LoginResultEnum res) {
        OAuth2EndpointUtils.throwError(res.getMsg(), res.getCode());
    }

    public static void throwError(String msg, int code) {
        throw new BusinessException(code, msg);
    }

    public static void throwAuthError(LoginResultEnum res) {
        OAuth2EndpointUtils.throwAuthError(res.getMsg(), res.getCode());
    }

    public static void throwAuthError(AuthResultEnum res) {
        OAuth2EndpointUtils.throwAuthError(res.getMsg(), res.getCode());
    }

    public static void throwAuthError(String msg, int code) {
        OAuth2Error error = new OAuth2Error("custom error ： ", msg + AuthConstant.EXCEPTION_SPLIT + code, null);
        throw new OAuth2AuthenticationException(error);
    }
}
